package top.xiewenwen.musicvisualizer;

import android.Manifest;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;


public class RecordFragment extends Fragment {

    private VisualizerInterface visualizerInterface;
    private AudioTrack audioTrack;
    private AudioRecord audioRecord;
    private static final int REQUEST_CODE = 1000; // 请求权限的请求码

    public RecordFragment(VisualizerInterface visualizerInterface) {
        this.visualizerInterface = visualizerInterface;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_record, container, false);

        // 设置音频录制参数
        int sampleRate = 44100; // 采样率
        int channelConfig = AudioFormat.CHANNEL_IN_MONO; // 单声道
        int audioFormat = AudioFormat.ENCODING_PCM_16BIT; // 16 位 PCM
        int bufferSize = AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat);
        if (ContextCompat.checkSelfPermission(requireContext(), android.Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            // 权限未被授予，进行请求
            ActivityCompat.requestPermissions(requireActivity(), new String[]{Manifest.permission.RECORD_AUDIO}, REQUEST_CODE);
        }
        //audioRecord = new AudioRecord(AudioManager.STREAM_MUSIC,sampleRate,channelConfig,audioFormat,bufferSize);
        //audioRecord.startRecording();
        audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, AudioFormat.CHANNEL_OUT_MONO, audioFormat, bufferSize, AudioTrack.MODE_STREAM);
        visualizerInterface.VisualizerGetSessionID(audioTrack.getAudioSessionId());
        //audioTrack.write(generatedSnd, 0, generatedSnd.length);
        audioTrack.play();

        return view;
    }

}